package artid.com.arttogo.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.hitomi.tilibrary.TransferImage;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import artid.com.arttogo.R;
import artid.com.arttogo.adapter.CelebritySealInfo_Adapter;
import artid.com.arttogo.bean.CelebritySealInfoParser;
import artid.com.arttogo.bean.ShowPhoto;
import artid.com.arttogo.db.Cache;
import artid.com.arttogo.network.VolleyBasic;
import artid.com.arttogo.network.VolleyCallback;
import artid.com.arttogo.network.VolleyData;
import artid.com.arttogo.network.VolleyMap;
import artid.com.arttogo.utils.NetUtils;
import artid.com.arttogo.utils.ToastUtil;
import artid.com.arttogo.view.DynamicHeightImageView;
import artid.com.arttogo.view.xlistview.PLA_AbsListView;
import artid.com.arttogo.view.xlistview.PLA_AdapterView;
import artid.com.arttogo.view.xlistview.XListView;

/**
 * 名人印章详情
 */

public class CelebritySealInfo_Activity extends BaseActivity implements View.OnClickListener, XListView.IXListViewListener {
    private View mHeadView;
    private TextView head_name, head_introduce;
    private ImageView head_downBtn;
    private boolean isRefreshed = false;// 是否刷新
    private int page = 1;
    private XListView mListView;
    private String CelebritySealID;//名人艺术家ID
    private String imgwide;// 请求的图片宽度
    private CelebrityInfo_Adapter mAdapter;
    private List<CelebritySealInfoParser.CelebritySealInfo_ImageInfo> list = new ArrayList<>();
    private List<CelebritySealInfoParser.CelebritySealInfo_ImageInfo> more_list = new ArrayList<>();
    private Boolean isOpen = false;//判断介绍是否展开
    private int dataNum;//数据总条数
    private int requestDataNum = 20;//请求数据数量
    private Boolean isLoad = true;//是否加载数据（默认可以加载）

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_celebritysealinfo);
        initView();
    }

    private void initView() {
        mContext = CelebritySealInfo_Activity.this;
        mBack = (ImageView) findViewById(R.id.back_btn);
        mBack.setOnClickListener(this);
        mTittle = (TextView) findViewById(R.id.tittle_text);
        mTittle.setText(getIntent().getStringExtra("CelebritySealName"));
        CelebritySealID = getIntent().getStringExtra("CelebritySealID");
        imgwide = (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 2) + "";
        mListView = (XListView) findViewById(R.id.CelebritySealInfo_listView);
        mListView.setPullRefreshEnable(false);
        mListView.setPullLoadEnable(false);
        mListView.setXListViewListener(this);
        mListView.setOnScrollListener(scrollListener);
        transferImage = TransferImage.getDefault(this);
        // 头布局
        mHeadView = View.inflate(this, R.layout.celebritysealinfo_head, null);
        head_name = (TextView) mHeadView.findViewById(R.id.celebritysealinfo_head_name);
        head_introduce = (TextView) mHeadView.findViewById(R.id.celebritysealinfo_head_introduce);
        head_downBtn = (ImageView) mHeadView.findViewById(R.id.celebritysealinfo_head_down);
        head_downBtn.setOnClickListener(this);
        // 头布局放入listView中
        mListView.addHeaderView(mHeadView);
        mListView.setOnItemClickListener(new PLA_AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(PLA_AdapterView<?> parent, View view,
                                    int Position, long id) {
                // TODO Auto-generated method stub
//                ToastUtil.toast(mContext, Position + "");
                int position = Position - 2;
                if (position >= 0) {
//                    ImageView thumImg = (ImageView) ((LinearLayout) mListView.getChildAt(position)).findViewById(R.id.itemCelebritysealInfo_img);
                    new TransferImage.Builder(CelebritySealInfo_Activity.this)
                            .setBackgroundColor(Color.parseColor("#FDFDFD"))
                            .setOriginImageList(originImgList)
                            .setImageUrlList(wrapOriginImageURL())
                            .setOriginIndex(position)
                            .setImageContent(testContent())
                            .setup(transferImage)
                            .show();
//                    List<ShowPhoto> showlist = new ArrayList<ShowPhoto>();
//                    for (int i = 0; i < more_list.size(); i++) {
//                        ShowPhoto item = new ShowPhoto();
//                        item.setUrl(more_list.get(i).getPath());
//                        item.setName(more_list.get(i).getName());
//                        showlist.add(item);
//                    }
//                    ShowPhoto mShowPhoto = new ShowPhoto();
//                    mShowPhoto.setList(showlist);
//                    Intent intent = new Intent(mContext, PhotoActivity.class);
//                    intent.putExtra("item", mShowPhoto);
//                    startActivity(intent);
                }
            }

        });
        getData(true);
    }

    List<ImageView> originImgList = new ArrayList<>();
//    /**
//     * 包装缩略图 ImageView 集合
//     *
//     * @return
//     */
//    @NonNull
//    private List<ImageView> wrapOriginImageViewList() {
//
////        mListView.getCount();
//        Log.e("T", "mListView.getCount()=" + mListView.getCount() + ",list.size()=" + list.size());
//        for (int i = 0; i < list.size(); i++) {
//            Log.e("T", "i=" + i);
//            ImageView thumImg = (ImageView) ((View) mListView.getChildAt(i + 2)).findViewById(R.id.itemCelebritysealInfo_img);
//            originImgList.add(thumImg);
//        }
//        return originImgList;
//    }

    /**
     * 瀑布流滑动事件
     */
    PLA_AbsListView.OnScrollListener scrollListener = new PLA_AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(PLA_AbsListView view, int scrollState) {

        }

        @Override
        public void onScroll(PLA_AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (more_list.size() != dataNum && isLoad == true) {
                //-11是数据已经显示一半的时候如果加头了就-12
                //-12是数据已经显示一半的时候（因为是瀑布流并且加了头所以-12）
                if (page == 1 && firstVisibleItem == (requestDataNum - 12)) {
                    page++;
                    getData(false);
                } else if (((page * requestDataNum) - 12) == firstVisibleItem) {
                    page++;
                    getData(false);
                }
            }
        }
    };


    /**
     * 包装缩略图 ImageView 集合
     *
     * @return
     */
    @NonNull
    private List<String> wrapOriginImageURL() {
        List<String> originImgList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            originImgList.add(list.get(i).getPath());
        }
        return originImgList;
    }

    /**
     * 包装缩略图 ImageView 集合
     *
     * @return
     */
    @NonNull
    private List<String> testContent() {
        List<String> ist = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            ist.add(list.get(i).getPath());
        }
        return ist;
    }

    @Override
    public void onRefresh() {
        // TODO Auto-generated method stub
        // 下拉刷新
        page = 1;
        isRefreshed = true;
        getData(false);
    }

    @Override
    public void onLoadMore() {
        // TODO Auto-generated method stub
        // 上拉加载
        page++;
        getData(false);
    }


    /**
     * 获取名人印章详情数据
     */
    private void getData(Boolean isLoadDialog) {
        isLoad = false;
        if (isLoadDialog) {
            VolleyBasic.showLoding(this);
        }
        VolleyBasic.getInstanceNoDialog(this).post(
                Cache.celebrityartistInfo,
                VolleyMap.getInstance().celebrityartistInfo(CelebritySealID, imgwide), CelebritySealInfoParser.class,
                new VolleyCallback() {
                    @SuppressWarnings({"unchecked", "static-access"})
                    @Override
                    public void onSuccess(VolleyData vd) {
                        isLoad = true;//如果加分页了释放改为true
                        // TODO Auto-generated method stub
                        if (isRefreshed) {
                            mListView.stopRefresh();
                        } else {
                            mListView.stopLoadMore();
                        }
                        CelebritySealInfoParser bean = (CelebritySealInfoParser) vd.getData();
                        if (bean != null) {
                            if (page == 1) {
                                setHeadView(bean);
                                try {
                                    JSONObject jsonObject = new JSONObject(vd.getJson());
                                    dataNum = jsonObject.getInt("num");
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                            list = bean.getImageinfo();
                            if (isRefreshed == true) {
                                more_list.clear();
                                isRefreshed = false;
                            }
                            if (!list.isEmpty()) {
                                more_list.addAll(list);
                            }

                            if (more_list.size() == 0) {
                                mListView.setPullLoadEnable(false);
                            } else {
                                mListView.setPullLoadEnable(true);
                            }
                            if (mAdapter == null) {
                                mAdapter = new CelebrityInfo_Adapter(mContext, more_list);
                                mListView.setAdapter(mAdapter);

                            }
                            mAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void onError(VolleyError volleyError) {
                        // TODO Auto-generated method stub
                        isLoad = true;
                        if (isRefreshed) {
                            mListView.stopRefresh();
                        } else {
                            mListView.stopLoadMore();
                        }
                    }
                });
    }

    private void setHeadView(CelebritySealInfoParser bean) {
        head_name.setText(bean.getRealname());
        setTextViewText(head_introduce, bean.getDescribe());
//        if (head_introduce.getMaxLines() > 1) {
//            head_downBtn.setVisibility(View.VISIBLE);
//            head_downBtn.setOnClickListener(this);
//            head_introduce.setEllipsize(TextUtils.TruncateAt.END); // 收缩
//        } else {
//            head_downBtn.setVisibility(View.GONE);
//        }
    }

    //超过三行折叠
    public static final String MainActivity = "MainActivity";
    private static final int VIDEO_CONTENT_DESC_MAX_LINE = 3;
    private static final int SHRINK_UP_STATE = 1;
    private static final int SPREAD_STATE = 2;
    private static int mState = SHRINK_UP_STATE;

    private void setTextViewText(TextView mContentText, String content) {
        mContentText.setText(content);
        mContentText.post(new StrecthRunnable(mContentText));
    }

    class StrecthRunnable implements Runnable {
        private TextView tvStrecth;

        public StrecthRunnable(TextView tvStrecth) {
            this.tvStrecth = tvStrecth;
        }

        public void run() {
            if (isStrecthShrink(tvStrecth)) {
                tvStrecth.setMaxLines(VIDEO_CONTENT_DESC_MAX_LINE);
                tvStrecth.setEllipsize(TextUtils.TruncateAt.END);
                head_downBtn.setVisibility(View.VISIBLE);
                head_downBtn.setImageResource(R.drawable.r_open);
            } else {
                head_downBtn.setVisibility(View.GONE);
            }
        }

    }

    private boolean isStrecthShrink(TextView mContentText) {
        int lines = mContentText.getLineCount();
        Log.d(MainActivity, "lines =" + lines);
        if (lines > VIDEO_CONTENT_DESC_MAX_LINE) {//
            return true;
        } else {
            return false;
        }
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_btn:
                finish();
                break;
            case R.id.celebritysealinfo_head_down: {
                if (mState == SPREAD_STATE) {
                    head_introduce.setMaxLines(VIDEO_CONTENT_DESC_MAX_LINE);
                    head_introduce.requestLayout();
                    head_downBtn.setImageResource(R.drawable.r_open);
                    mState = SHRINK_UP_STATE;
                } else if (mState == SHRINK_UP_STATE) {//
                    head_introduce.setMaxLines(Integer.MAX_VALUE);
                    head_introduce.requestLayout();
                    head_downBtn.setImageResource(R.drawable.r_close);
                    mState = SPREAD_STATE;
                }
                break;
            }
            default: {
                break;
            }
        }
    }

    class CelebrityInfo_Adapter extends BaseAdapter {
        private Context mContext;
        private List<CelebritySealInfoParser.CelebritySealInfo_ImageInfo> list;

        public CelebrityInfo_Adapter(Context mContext, List<CelebritySealInfoParser.CelebritySealInfo_ImageInfo> list) {
            this.mContext = mContext;
            this.list = list;
        }

        public void notifyData(List<CelebritySealInfoParser.CelebritySealInfo_ImageInfo> list) {
            // TODO Auto-generated method stub
            this.list = list;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            ViewHolder holder = null;
            View v = convertView;
            if (v == null) {
                holder = new ViewHolder();
                v = LayoutInflater.from(mContext).inflate(R.layout.item_celebritysealinfo, null);
                holder.img = (DynamicHeightImageView) v.findViewById(R.id.itemCelebritysealInfo_img);
                holder.describe = (TextView) v.findViewById(R.id.itemCelebritysealInfo_describe);
                v.setTag(holder);
            } else {
                holder = (ViewHolder) v.getTag();
            }
            holder.img.setHeight(Integer.parseInt(list.get(position).getHeight()));
            originImgList.add(holder.img);
            ImageLoader.getInstance().displayImage(list.get(position).getPath()
                    + "_" + (Integer.parseInt(NetUtils.getDisplayMetrics((Activity) mContext).get(NetUtils.DM_WIDTH)) / 2) + "x10.png", holder.img);
            holder.describe.setText(list.get(position).getName());
            return v;
        }

        class ViewHolder {
            DynamicHeightImageView img;
            TextView describe;
        }
    }
}